package com.wngbms.netty.seatdemo.service;

import com.alibaba.fastjson.JSON;
import com.wngbms.netty.seatdemo.bean.SeatEvent;
import com.wngbms.netty.seatdemo.comm.*;
import com.wngbms.netty.seatdemo.message.BaseHeader;
import com.wngbms.netty.seatdemo.message.SeatInMessage;
import com.wngbms.netty.seatdemo.message.SeatOutMessage;
import com.wngbms.netty.seatdemo.server.SeatBizHandler;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Slf4j
public class HangUpHandler implements SeatTypeHandler {
    public static final CmdType CMD_TYPE = CmdType.HANGUP;

    @Override
    public void handleInbound(SeatInMessage seatInMessage) {
        byte[] body = seatInMessage.getBody();
        log.info("挂断处理:{}", new String(body, StandardCharsets.UTF_8));
    }

    @Override
    public void handleOutbound(String userId) {
        log.info("推送挂断指令:{}", userId);
        SeatEvent seatEvent = new SeatEvent();
        seatEvent.setEventId(UUID.randomUUID().toString().replace("-", ""));
        byte[] bytes = JSON.toJSONString(seatEvent).getBytes(StandardCharsets.UTF_8);
        BaseHeader baseHeader = BaseHeader.build(MagicVersion.V1, CmdType.HANGUP,
                BodyType.JSON, EncryptionType.NON, ReqOrResp.REQ, bytes.length);

        Channel channel = SeatBizHandler.USER_CHANNEL_MAP.get(userId);
        SeatOutMessage seatOutMessage = new SeatOutMessage();
        seatOutMessage.setBaseHeader(baseHeader);
        seatOutMessage.setBody(bytes);
        channel.writeAndFlush(seatOutMessage);
    }
}
